package lock_thread;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/5/9
 * Time:10:09
 * 死锁
 **/
public class Demo6 {
    public static void main(String[] args) {
        //锁A(资源A)
        Object lockA = new Object();
        //锁B(资源B)
        Object lockB = new Object();

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                //得到锁A
                synchronized (lockA) {
                    System.out.println("线程1得到了锁A");
                }
                try {
                    //休眠1s，让线程2先得到锁B
                    Thread.sleep(1000);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程1等待获取锁B");
                //尝试获取资源B
                synchronized (lockB) {
                    System.out.println("线程1得到了锁B");
                }
            }
        }, "t1");
        t1.start();

        //创建并启动线程2
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                //得到锁B
                synchronized (lockB) {
                    System.out.println("线程2得到了锁B");
                }
                try {
                    //休眠1s，让线程1先得到锁A
                    Thread.sleep(1000);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程2等待获取锁A");
                //尝试获取资源A
                synchronized (lockA) {
                    System.out.println("线程2得到了锁A");
                }
            }
        }, "t2");
        t2.start();
    }
}
